<template>
  <div class="app-container">
    <el-card class="table_style">
      <el-form ref="ruleForm" :model="category" :rules="rules" label-width="100px">
        <el-form-item label="上级栏目" prop="parent_id">
          <el-select v-model="category.parentId" placeholder="顶级栏目">
            <el-option :value="0" label="顶级栏目" disabled />
            <el-option v-for="item in categories" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="分类名称" prop="name">
          <el-input v-model="category.name" />
        </el-form-item>

        <el-form-item v-if="category.parentId === 0" label="缩略图" prop="image">
          <el-upload
            class="avatar-uploader"
            :data="qiniuForm"
            :before-upload="beforeUpload"
            :on-success="uploadSuccess"
            action="https://upload.qiniup.com"
          >
            <img v-if="category.image" :src="category.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>

        <el-form-item label="栏目排序" prop="sort">
          <el-input-number v-model="category.sort" :min="1" :max="99" @change="handleChange" />
        </el-form-item>

        <el-form-item>
          <el-button @click="resetForm('ruleForm')">返回首页</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">立即保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { updateCategory, fetchCategory, fetchCategoryList } from '@/api/category'
import { fetchUpload } from '@/api/upload'

const { v4: uuidv4 } = require('uuid')
export default {
  data() {
    return {
      categories: [],
      category: {
        parentId: '',
        name: '',
        sort: '99',
        image: ''
      },
      qiniuForm: {
        key: '', // 文件名称
        token: ''
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入栏目名称',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 8,
            message: '长度在 2 到 8 个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      fetchCategoryList().then((res) => {
        this.categories = res.data.categories
      })

      fetchCategory(this.$route.params.id).then((res) => {
        this.category = res.data.category
      })
    },
    // 上传之前
    async beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG或PNG 格式!')
      }

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }

      // 如果验证失败，返回假
      if (isJPG && isLt2M === false) return false

      // 如果验证成功，获取token
      const fileType = file.type === 'image/jpeg' ? 'jpg' : 'png' // 获取扩展名
      const res = await fetchUpload()
      this.qiniuForm = {
        key: `${uuidv4()}.${fileType}`, // 文件名称
        token: res.data.uploadToken
      }
      return true
    },

    // 上传成功，获取图片地址
    uploadSuccess(res) {
      this.category.image = 'https://image.holyzq.com/' + res.key
    },
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (!valid) return
        updateCategory(this.$route.params.id, this.category).then((res) => {
          if (res.code === 20000) {
            this.$message({
              message: res.message,
              type: 'success'
            })
            this.$router.push({ name: 'Category' })
          }
        })
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleChange(value) {
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
